{% extends 'base.html' %}

{% load url_utils %}

{% block right_content %}

    <!-- 右侧内容 -->
     <div class="right">
        <!-- 顶部搜索 -->
        <div class="top">
            <div class="tool">
                <div class="class-info">
                    <form method="get" action="/students/">
                        <span>班级：</span>
                        <select name="grade" id="id_grade">
                            <option value="" selected="">请选择班级</option>
                            {% for grade in grades %}
                            <option value="{{ grade.pk }}" {% if grade.pk|stringformat:"s" == current_grade %} selected {% endif %}>
                                {{ grade.grade_name }}
                            </option>
                            {% endfor %}
                        </select>
                        <span>&thinsp;&thinsp;&thinsp;</span>
                        <span>姓名/学号</span>
                        <input type="text" name="search" placeholder="姓名/学号" value="">
                        <input type="submit" value="搜索">
                        <span>&thinsp;&thinsp;&thinsp;</span>
                        <button type="button" class="add" id="add">新增</button>
                        <button type="button" class="del" id="del-all" style="background-color: red; color: aliceblue;">批量删除</button>
                        <button type="button" class="import" id="import">导入</button>
                        <button type="button" class="export" id="export">导出</button>
                    </form>
                </div>
            </div>
        </div>

        <!-- 底部数据展示 -->
        <div class="bottom">
        <table>
            <thead>
                <tr>
                    <th><input type="checkbox" id="select-all"></th>
                    <th>姓名</th>
                    <th>学号</th>
                    <th>班级</th>
                    <th>性别</th>
                    <th>生日</th>
                    <th>联系方式</th>
                    <!-- <th>地址</th> -->
                    <th>操作</th>
                </tr>
            </thead>
            <tbody> 
                {% for student in students %}
                <tr>
                    <td><input type="checkbox" name="student_ids" value="{{ student.pk }}"></td>
                    <td>{{ student.student_name }}</td>
                    <td>{{ student.student_number }}</td>
                    <td>{{ student.grade }}</td>
                    <td>{{ student.gender }}</td>
                    <td>{{ student.birthday }}</td>
                    <td>{{ student.contact }}</td>
                    <!-- <td>{{ student.address }}</td> -->
                    <td>
                        <a href="{% url 'student_update' student.pk %}" class="btn btn-primary btn-sm edit" style="color: green;"> 
                            <!-- <button class="add">编辑</button> -->
                             编辑
                        </a>
                        <a href="{% url 'student_delete' student.pk %}" class="btn btn-danger btn-sm del" style="color: red;">
                            <!-- <button class="delete">删除</button> -->
                             删除
                        </a>
                        
                    </td>

                </tr>
                {% endfor %}

            </tbody>

        </table>
        <!-- 分页导航 -->
        <div class="pagination">
            <span class="step-links">
                {% if page_obj.has_previous %}
                    <!-- <a href="?page=1">&laquo; 首页</a> -->
                    <!-- <a href="?page=page_obj.previous_page_number">&laquo; 上一页</a> -->
                    <a href="?{% search_url request page=1 %}">&laquo; 首页</a>
                    <a href="?{% search_url request page=page_obj.previous_page_number %}">上一页</a>
                {% endif %}

                <span class="current">
                    {{ page_obj.number }} / {{ page_obj.paginator.num_pages }}
                </span>

                {% if page_obj.has_next %}
                    <!-- <a href="?page={{ page_obj.next_page_number }}">下一页</a> -->
                    <!-- <a href="?page={{ page_obj.paginator.num_pages }}">末页 &raquo;</a> -->
                    <a href="?{% search_url request page=page_obj.next_page_number %}">下一页</a>
                    <a href="?{% search_url request page=page_obj.paginator.num_pages %}">末页</a>

                {% endif %} 
            </span>

        </div>

        </div>
        
     </div>
<script>
    //选中所有学生
    document.addEventListener('DOMContentLoaded', function(){
        //获取全选复选框元素
        const selectAllCheckbox = document.getElementById('select-all');
        
        //监听全选复选框的点击事件
        selectAllCheckbox.addEventListener('change', function(){
            //获取所有 name为student_ids 的复选框
            const studentCheckboxes = document.querySelectorAll('input[name="student_ids"]');

            //根据全选复选框的选中状态设置每个学生复选框的状态
            studentCheckboxes.forEach(function(checkbox){
                checkbox.checked = selectAllCheckbox.checked
            })
        })
    })

    // 点击新增
    document.getElementById('add').addEventListener('click', function() {
            Swal.fire({
                position: 'top-end',
                html: `<iframe src="{% url 'student_create' %}" width="100%" height="800px" frameborder="0"> </iframe>`,
                width: 650,
                showConfirmButton: false,
            });
    });

    // 点击编辑
    document.querySelectorAll('.edit').forEach(button => {
        button.addEventListener('click', function(e){
            e.preventDefault(); //阻止跳转
           
            url = this.getAttribute('href')
            console.log(url)
            //弹窗
            Swal.fire({
                position: 'top-end',
                html: `<iframe src="${url}" width="100%" height="800px" frameborder="0"> </iframe>`,
                width: 650,
                showConfirmButton: false,
            });
        })
    })

    //点击删除
    document.querySelectorAll('.btn-danger').forEach(button => {
        button.addEventListener('click', function(e){
            e.preventDefault(); //阻止跳转
           
            url = this.getAttribute('href')
            console.log(url)
            //弹窗
            Swal.fire({
                title: '确认删除',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: '删除',
                confirmButtonColor: '#d33',
            })
            .then((reslut) => { //按下确认按键之后 执行
                if (reslut.isConfirmed){
                    fetch(url, {
                        method: 'DELETE',
                        headers:{
                            'x-Requested-With': 'XMLHttpRequest',
                            'X-CSRFToken': '{{ csrf_token }}', // 添加CSRF令牌
                        },
                    })
                    .then(response => response.json())
                    .then(data => {
                        console.log(data)
                        if (data.status === 'success'){
                            Swal.fire("Deleted! hhhh!", data.messages, "success");
                            window.location.reload();
                        }else{
                            Swal.fire("Failure! hhhh!", data.messages, "error");
                            window.location.reload();
                        }
                    })
                }
            })
        })
    })

    //批量删除
    document.getElementById('del-all').addEventListener('click', function(){
        //是否有学生被选中
        const checkboxes = document.querySelectorAll('input[name="student_ids"]:checked');

        if(checkboxes.length === 0){
            Swal.fire({
                title: '错误',
                text: '请选中要删除的学生',
                icon: 'error',
                confirmButtonText:'好的',
            });
            return ;
        }
        Swal.fire({
            title: '确认删除选中的数据：' + checkboxes.length + "条",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: "#d33",
            confirmButtonText:'删除',
        })
        .then((reslut) => {
            if (reslut.isConfirmed){
                console.log("删除任务")
                const formData = new FormData;

                checkboxes.forEach((checkbox) => {
                    formData.append('student_ids', checkbox.value)
                })

                fetch("{% url 'student_bulk_delete' %}", {
                    method: 'POST',
                    headers:{
                        'x-Requested-With': 'XMLHttpRequest',
                        'X-CSRFToken': '{{ csrf_token }}', // 添加CSRF令牌
                    },
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    console.log(data);
                    if(data.status === 'success'){
                        Swal.fire("Deleted! hhhh!", data.messages, "success");
                        window.location.reload();
                    }else{
                        Swal.fire("Failure! hhhh!", data.messages, "error");
                        window.location.reload();
                    }
                })
            }
        })
    })

    //导入
    document.getElementById('import').addEventListener('click', function(){
        Swal.fire({
            title: "上传学生信息Excel",
            input: "file",
            inputAttributes: {
                "accept": ".xlsx",
                "aria-label": "上传学生excel表"
            },
            showCancelButton: true,
            confirmButtonText: '上传',
            showLoaderOnConfirm: true,
            preConfirm: (file) => {
                //处理文件上传的逻辑 使用FormData 和 Fetch API 上传文件
                const formData = new FormData();
                formData.append('excel_file', file);

                return fetch('{% url "upload_student" %}', {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': '{{ csrf_token }}',
                    },
                    body: formData,
                })
                .then(response => response.json())
                .then(data => {
                    // console.log(data);
                    if(data.status ==='error'){
                        throw new Error(data.messages);
                    }
                })
                .catch(error => {
                    console.log(error);
                    Swal.showValidationMessage(`${error.messages || error}`);
                });
            },
            allowOutsideClick: () => !Swal.isLoading()
        }).then((reslut) => {
            if (reslut.isConfirmed) {
                Swal.fire({
                    title:'上传成功啦!',
                    confirmButtonText:'好的',
                    icon: 'success',
                })
                window.location.reload();
            }
        })
    })
    
    //导出
    document.getElementById('export').addEventListener('click', function(){
        var select = document.querySelector('select[name="grade"]');
        var value = select.value;
        var gradeText = select.options[select.selectedIndex].text;


        console.log(gradeText);
        if (!value){
            Swal.fire({
                title:'错误！',
                text:'请选择一个班级',
                icon:'error',
                confirmButtonText:'确定',
            });
            return ;
        }
        Swal.fire({
            title:'确认',
            text:'导出【'+ gradeText +'】学生信息',
            icon:'warning',
            showCancelButton: true,
            confirmButtonText:'确定',
            cancelButtonText:"取消",
        })
        .then(reslut => {
            fetch('{% url "export_excel" %}', {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}',
                },
                body: JSON.stringify({grade: value})
            }).then(response => {
                if (!response.ok){
                    response.json()
                    .then(reslut => {
                        Swal.fire({
                            title: '下载失败',
                            text: '服务器错误：' + reslut.messages,
                            icon: 'error',
                            confirmButtonText: '关闭',
                        });
                    });
                    throw new Error('网络或服务器错误');
                }
                return response.blob();
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = gradeText + '.xlsx';
                a.click();

                // 清理并移除元素
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            })
            .catch(error => {
                console.error('下载失败', error);
                Swal.fire({
                    title: '错误',
                    text: '下载出现问题，请稍后下载。',
                    icon: 'error',
                    confirmButtonText: '关闭',
                });
            }); 
        })
    })

</script>

{% endblock %}